import { useState, useEffect } from "react";
import { Button, Form, Input, Checkbox } from "antd";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import DingTalk from "../../asserts/dingtalk.svg";
import API from "@src/api";
import md5 from "js-md5";

const { Login, DingTalkLogin } = API.globalAPI;

function AccountLogin() {
	const [loading, setLoading] = useState(false);
	const [remember, setRemenber] = useState(true);
	const [form] = Form.useForm();

	useEffect(() => {
		const remember = localStorage.getItem("rememberAccount");
		const param = localStorage.getItem("accountInfo");
		if (!!remember && !!param) {
			// 如果已经记住密码了,就考虑直接进入内容
			form.setFieldsValue(JSON.parse(param));
			setRemenber(true);
		}
		// eslint-disable-next-line
	}, []);

	const changeRemember = (e) => {
		setRemenber(e.target.checked);
	};
	const login = () => {
		form.validateFields().then((resA) => {
			const param = {
				password: md5(resA.password),
				username: resA.username,
			};
			setLoading(true);
			Login(param)
				.then((res) => {
					if (!!remember) {
						localStorage.setItem("rememberAccount", "true");
						localStorage.setItem(
							"accountInfo",
							JSON.stringify(resA)
						);
					} else {
						localStorage.removeItem("rememberAccount");
						localStorage.removeItem("accountInfo");
					}
					sessionStorage.setItem("AuthorizationCode", res.data);
					setLoading(false);
					let str = window.location.href.replace("#/login", "");
					window.location.href = str.split("?")[0] + "#/system";
				})
				.catch(() => {
					setLoading(false);
				});
		});
	};
	const dingTalkLogin = () => {
		let params = { url: window.location.href.toString() };
		DingTalkLogin({ ...params }).then((res) => {
			window.location.href = res.data;
		});
	};
	return (
		<>
			<Form form={form}>
				<Form.Item
					name="username"
					rules={[{ required: true, message: "请填写账号" }]}
					getValueFromEvent={(e) => {
						return e.target.value.trim();
					}}
				>
					<Input
						placeholder="请输入账号"
						size="large"
						prefix={<UserOutlined />}
					/>
				</Form.Item>
				<Form.Item
					name="password"
					rules={[{ required: true, message: "请填写密码" }]}
					getValueFromEvent={(e) => {
						return e.target.value.trim();
					}}
				>
					<Input.Password
						placeholder="请输入密码"
						size="large"
						prefix={<LockOutlined />}
					/>
				</Form.Item>
			</Form>
			<div>
				<Checkbox
					style={{ color: "#9ea8b8" }}
					checked={remember}
					onChange={changeRemember}
				>
					记住账号和密码
				</Checkbox>
			</div>
			<Button
				block
				size="large"
				type="primary"
				onClick={login}
				className="the-button"
				loading={loading}
			>
				登录
			</Button>
			<div className="normal-flex">
				<span>其他登录方式：</span>
				<img
					className="the-dingtalk"
					src={DingTalk}
					alt=""
					onClick={dingTalkLogin}
				/>
			</div>
		</>
	);
}

export default AccountLogin;
